package com.haowen.dao;

import com.haowen.model.Message;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface MessageMapper {
    @Insert("INSERT INTO message (from_user_id,to_user_id,content,create_time,is_read,type) " +
            "VALUES (#{fromUserId},#{toUserId},#{content},#{createTime},#{isRead},#{type})")
    int insert(Message message);

    @Select("SELECT m.*, " +
            "f.username as fromUserName, " +
            "t.username as toUserName " +
            "FROM message m " +
            "LEFT JOIN consumer f ON m.from_user_id = f.id " +
            "LEFT JOIN consumer t ON m.to_user_id = t.id " +
            "WHERE m.to_user_id = #{userId} " +
            "ORDER BY m.create_time DESC")
    List<Message> selectReceivedMessages(Integer userId);

    @Select("SELECT m.*, " +
            "f.username as fromUserName, " +
            "t.username as toUserName " +
            "FROM message m " +
            "LEFT JOIN consumer f ON m.from_user_id = f.id " +
            "LEFT JOIN consumer t ON m.to_user_id = t.id " +
            "WHERE m.from_user_id = #{userId} " +
            "ORDER BY m.create_time DESC")
    List<Message> selectSentMessages(Integer userId);

    @Update("UPDATE message SET is_read = #{status} WHERE id = #{messageId}")
    int updateReadStatus(@Param("messageId") Integer messageId, @Param("status") Integer status);

    @Select("SELECT COUNT(*) FROM message WHERE to_user_id = #{userId} AND is_read = 0")
    int selectUnreadCount(Integer userId);

    @Delete("DELETE FROM message WHERE id = #{messageId}")
    int delete(Integer messageId);
}
